from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from snownlp import SnowNLP
import os

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///sentiment.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

# 定义数据模型
class AnalysisRecord(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    text = db.Column(db.Text, nullable=False)
    sentiment = db.Column(db.String(20), nullable=False)
    confidence = db.Column(db.Float, nullable=False)
    create_time = db.Column(db.DateTime, default=datetime.utcnow)

# 创建数据库表
with app.app_context():
    db.create_all()

# 情感分析API
@app.route('/api/analyze', methods=['POST'])
def analyze_text():
    data = request.json
    text = data.get('text')
    if not text:
        return jsonify({'error': 'Missing text parameter'}), 400
    
    # 使用SnowNLP进行情感分析
    s = SnowNLP(text)
    sentiment_score = s.sentiments
    
    # 判断情感类别
    if sentiment_score >= 0.7:
        sentiment = '积极'
    elif sentiment_score <= 0.3:
        sentiment = '消极'
    else:
        sentiment = '中性'
    
    # 保存记录
    record = AnalysisRecord(
        text=text,
        sentiment=sentiment,
        confidence=sentiment_score
    )
    db.session.add(record)
    db.session.commit()
    
    return jsonify({
        'text': text,
        'sentiment': sentiment,
        'confidence': sentiment_score,
        'record_id': record.id
    })

# 获取历史记录API
@app.route('/api/history', methods=['GET'])
def get_history():
    records = AnalysisRecord.query.order_by(AnalysisRecord.create_time.desc()).all()
    history = [{
        'id': record.id,
        'text': record.text,
        'sentiment': record.sentiment,
        'confidence': record.confidence,
        'create_time': record.create_time.strftime('%Y-%m-%d %H:%M:%S')
    } for record in records]
    return jsonify(history)

if __name__ == '__main__':
    app.run(debug=True)    